﻿namespace QFramework
{
    using UnityEditor;
    using System.Collections.Generic;
    using FairyGUI;
    using UnityEngine;
    using FairyGUIEditor;

    public class FGUI_QFrameworkEditor : EditorWindow
    {
        private const string ByteLabel = "desc";
        private const string ResLabel = "res";
        private const string Bytesuffix = ".bytes";

        bool isDraw;
        List<UIPackage> m_PackList;
        Dictionary<UIPackage, List<PackageItem>> m_CurrentList;
        UIPackage m_CurrentPackage;

        Vector2 ScrollViewPack;
        Vector2 ScrollViewCom;

        [MenuItem("Assets/[FGUI] - LoadResAndCreateCode")]
        static void Open()
        {
            EditorToolSet.LoadPackages();
            _FlagABRes();

            FGUI_QFrameworkEditor windows = EditorWindow.GetWindowWithRect<FGUI_QFrameworkEditor>(new Rect(0, 0, 600, 420), false);
            windows.Init();
            windows.Show();
        }

        /// <summary>
        /// 资源初始化
        /// </summary>
        void Init()
        {
            m_CurrentPackage = null;
            m_PackList = new List<UIPackage>();
            m_CurrentList = new Dictionary<UIPackage, List<PackageItem>>();
            m_PackList = _GetPackName();
            isDraw = true;
        }

        private void OnProjectChange()
        {
            isDraw = false;
        }

        private void OnEnable()
        {
            EditorToolSet.LoadPackages();
            Init();
            isDraw = true;
        }

        private void OnGUI()
        {
            if (!isDraw)
                return;

            GUI.Box(new Rect(0, 0, 300, 400), "");

            GUILayout.BeginArea(new Rect(0, 10, 300, 400));
            {
                ScrollViewPack = EditorGUILayout.BeginScrollView(ScrollViewPack, false, false);
                EditorGUILayout.BeginVertical();
                for (int i = 0; i < m_PackList.Count; i++)
                {
                    GUILayout.Space(3);
                    if (GUILayout.Button(m_PackList[i].name, "CapsuleButton"))
                    {
                        m_CurrentPackage = m_PackList[i];
                        if (!m_CurrentList.ContainsKey(m_PackList[i]))
                        {
                            m_CurrentList.Add(m_PackList[i], new List<PackageItem>());
                        }
                    }
                }
                EditorGUILayout.EndVertical();
                EditorGUILayout.EndScrollView();
            }
            GUILayout.EndArea();

            GUI.Box(new Rect(300, 0, 300, 400), "");
            GUILayout.BeginArea(new Rect(300, 10, 300, 380));
            {
                ScrollViewCom = EditorGUILayout.BeginScrollView(ScrollViewCom, false, false);
                EditorGUILayout.BeginVertical();

                if (m_CurrentPackage != null)
                {
                    for (int i = 0; i < m_CurrentPackage.GetItems().Count; i++)
                    {
                        if (m_CurrentPackage.GetItems()[i].type == PackageItemType.Component)
                        {
                            if (m_CurrentList.ContainsKey(m_CurrentPackage))
                            {
                                if (m_CurrentList[m_CurrentPackage].Contains(m_CurrentPackage.GetItems()[i]))
                                {
                                    if (GUILayout.Button(m_CurrentPackage.GetItems()[i].name, "CN CountBadge"))
                                    {
                                        m_CurrentList[m_CurrentPackage].Remove(m_CurrentPackage.GetItems()[i]);
                                    }
                                }
                                else
                                {
                                    if (GUILayout.Button(m_CurrentPackage.GetItems()[i].name, "CapsuleButton"))
                                    {
                                        m_CurrentList[m_CurrentPackage].Add(m_CurrentPackage.GetItems()[i]);
                                    }
                                }
                            }
                        }
                    }
                }
                EditorGUILayout.EndVertical();
                EditorGUILayout.EndScrollView();
            }
            GUILayout.EndArea();

            GUILayout.BeginArea(new Rect(300, 400, 300, 20));
            if (GUI.Button(new Rect(130, 0, 70, 20), "Refresh"))
            {
                Init();
            }
            if (GUI.Button(new Rect(200, 0, 100, 20), "CreateUICode"))
            {
                foreach (var item in m_CurrentList)
                {
                    _CreateUICode(item.Key, item.Value);
                    Init();
                }
            }
            GUILayout.EndArea();

        }

        private static List<UIPackage> _GetPackName()
        {
            return UIPackage.GetPackages();
        }

        /// <summary>
        /// 标记ab资源
        /// </summary>
        private static void _FlagABRes()
        {
            var pkgs = _GetPackName();

            foreach (var Pack in pkgs)
            {
                string[] ids = AssetDatabase.FindAssets(Pack.name + "@");
                ids.ForEach(x =>
                {
                    MarkAB(AssetDatabase.GUIDToAssetPath(x), Pack.name + ResLabel);
                });

                string assetpath = AssetDatabase.GUIDToAssetPath(ids[0]);
                int pos = assetpath.LastIndexOf("@");

                if (pos == -1)
                    continue;
                Log.I(Pack.assetPath);
                assetpath = assetpath.Substring(0, pos);
                MarkAB(assetpath + Bytesuffix, Pack.name + ByteLabel);

                // _CreateUICode(Pack);
            }
            AssetDatabase.Refresh();
        }

        /// <summary>
        /// 设置ab包
        /// </summary>
        /// <param name="path"></param>
        /// <param name="name"></param>
        private static void MarkAB(string path, string name)
        {
            AssetImporter m_CurrentImporter = AssetImporter.GetAtPath(path);
            if (m_CurrentImporter.assetBundleName != string.Empty)
                m_CurrentImporter.assetBundleName = name;
        }

        /// <summary>
        /// 创建UI脚本 控制脚本、组件脚本、资源脚本。
        /// </summary>
        /// <param name="Pack"></param>
        private static void _CreateUICode(UIPackage Pack, List<PackageItem> m_Item)
        {
            FGUICodeGenerator.BeginSource();

            List<PackageItem> SourceItemList = Pack.GetItems();

            SourceItemList.ForEach(x =>
            {
                switch (x.type)
                {
                    case PackageItemType.Image:
                        FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Source_Image, x.name);
                        break;
                    case PackageItemType.Font:
                        FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Source_Font, x.name);
                        break;
                    case PackageItemType.Atlas:
                        FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Source_Atlas, x.name);
                        break;
                    case PackageItemType.Misc:
                        FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Source_Misc, x.name);
                        break;
                    case PackageItemType.MovieClip:
                        FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Source_MovieClip, x.name);
                        break;
                    case PackageItemType.Sound:
                        FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Source_sound, x.name);
                        break;
                }
            }
            );


            for (int i = 0; i < m_Item.Count; i++)
            {
                var x = m_Item[i];

                EditorUtility.DisplayProgressBar("[FGUI] - LoadResAndCreateCode", "current script progress", ((float)i / (float)m_Item.Count));

                switch (x.type)
                {
                    case PackageItemType.Component:

                        FGUICodeGenerator.BeginCom(Pack.name, x.name);
                        GComponent tempData = ((GComponent)UIPackage.CreateObject(Pack.name, x.name));
                        tempData.Controllers.ForEach
                        (
                            y => FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Controllers, y.name)
                        );
                        tempData.GetChildren().ForEach
                        (
                            y => FGUICodeGenerator.AddInfo(FGUICodeGenerator.FguiType.Children, y.name)
                        );
                        FGUICodeGenerator.CreateCode();
                        tempData.Dispose();

                        break;
                }
            }

            FGUICodeGenerator.CreateResCode();
            EditorUtility.ClearProgressBar();
        }
    }
}
